/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.upn.sigemfi.gar.bc;

import edu.upn.sigemfi.gar.be.Agricola;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author Freddy
 */
public class AgricolaDelegate {

    private AgricolaFacadeLocal local;

    public AgricolaDelegate(){
        local = lookupAgricolaFacade();
    }

    private AgricolaFacadeLocal lookupAgricolaFacade() {
        try {
            Context c = new InitialContext();
            return (AgricolaFacadeLocal) c.lookup("java:comp/env/AgricolaFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }

    public void crear(Agricola agricola) throws Exception
    {
        try{
            local.create(agricola);
        }
        catch(Exception ex){
            local=lookupAgricolaFacade();
            throw new Exception("Crear Agricola"+ex.getMessage());
        }
    }

    public void editar(Agricola agricola) throws Exception
    {
        try{
            local.edit(agricola);
        }catch (Exception ex){
            local=lookupAgricolaFacade();
            throw new Exception("Editar Agricola"+ex.getMessage());
        }
    }

    public void eliminar(Agricola agricola) throws Exception
    {
        try{
            local.remove(agricola);
        }
        catch(Exception ex){
            local=lookupAgricolaFacade();
            throw new Exception("Crear Agricola"+ex.getMessage());
        }
    }

    public List<Agricola> listar() throws Exception {
        try {
            return local.findAll();
        } catch (Exception e) {
            local = lookupAgricolaFacade();
            throw new Exception("Listar Agricolas. " + e.getMessage(), e);
        }
    }

    public Agricola buscar(Long codigo) throws Exception {
        try {
            return local.find(codigo);
        } catch (Exception e) {
            local = lookupAgricolaFacade();
            throw new Exception("Buscar Agricola. " + e.getMessage(), e);
        }
    }
}